﻿/*
 Author:du
 Time:2017.11.7
*/

using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class SVNTool
{
    private const string svnProcPathKey = "SvnProcPathKey";

    private static List<string> m_drives = new List<string>() { "c:", "d:", "e:", "f:" };
    private static string m_svnPath = @"\Program Files\TortoiseSVN\bin\";
    private static string m_svnProc = @"TortoiseProc.exe";
    private static string m_svnProcPath = "";

    [MenuItem("Assets/[FC SVN]/提交", false, -10001)]
    public static void CommitToSVN()
    {
        if (string.IsNullOrEmpty(m_svnProcPath))
            m_svnProcPath = GetSvnProcPath();

        AssetDatabase.SaveAssets();
        string path = Application.dataPath.Replace('/', '\\');
        string para = "/command:commit /path:\"" + path + "\"";
        System.Diagnostics.Process.Start(m_svnProcPath, para);
    }

    [MenuItem("Assets/[FC SVN]/更新", false, -10000)]
    public static void UpdateFromSVN()
    {
        if (string.IsNullOrEmpty(m_svnProcPath))
            m_svnProcPath = GetSvnProcPath();

        DirectoryInfo dir = new DirectoryInfo(Application.dataPath);
        string path = dir.Parent.FullName.Replace('/', '\\');
        string para = "/command:update /path:\"" + path + "\" /closeonend:0";
        Start(para);
    }

    private static void Start(string para)
    {
        try
        {
            System.Diagnostics.Process.Start(m_svnProcPath, para);
        }
        catch
        {
            m_svnProcPath = "";
            EditorPrefs.SetString(svnProcPathKey, m_svnProcPath);
        }
    }

    private static string GetSvnProcPath()
    {
        string path = EditorPrefs.GetString(svnProcPathKey);
        if (path != null && path != "")
        {
            return path;
        }
        foreach (string item in m_drives)
        {
            string searchPath = string.Concat(item, m_svnPath, m_svnProc);
            if (File.Exists(searchPath))
                return searchPath;
        }
        path = EditorUtility.OpenFilePanel("Select TortoiseProc.exe", "c:\\", "exe");
        EditorPrefs.SetString(svnProcPathKey, path);
        return path;
    }
}